'use strict';

/**
 * 用户模型
 * @param app
 */
module.exports = app => {
  const { STRING, INTEGER, BOOLEAN, DATE, BIGINT } = app.Sequelize;

  const User = app.model.define('sys_users', {
    id: {
      type: BIGINT,
      primaryKey: true,
      comment: '用户ID',
    },
    username: {
      type: STRING(50),
      allowNull: false,
      unique: true,
      comment: '用户名',
    },
    password: {
      type: STRING(100),
      allowNull: false,
      comment: '密码',
    },
    realName: {
      type: STRING(50),
      allowNull: true,
      comment: '真实姓名',
      field: 'real_name',
    },
    email: {
      type: STRING(100),
      allowNull: true,
      comment: '邮箱',
    },
    phone: {
      type: STRING(20),
      allowNull: true,
      comment: '电话',
    },
    avatar: {
      type: STRING(255),
      allowNull: true,
      comment: '头像',
    },
    status: {
      type: BOOLEAN,
      defaultValue: true,
      comment: '状态：true启用，false禁用',
    },
    departmentId: {
      type: BIGINT,
      allowNull: true,
      comment: '部门ID',
      field: 'department_id',
    },
    createTime: {
      type: DATE,
      allowNull: false,
      comment: '创建时间',
      field: 'create_time',
      defaultValue: app.Sequelize.NOW,
    },
    updateTime: {
      type: DATE,
      allowNull: false,
      comment: '更新时间',
      field: 'update_time',
      defaultValue: app.Sequelize.NOW,
    },
  });

  // 在创建前生成雪花ID
  User.beforeCreate((user) => {
    const SnowflakeUtil = require('../utils/snowflake');
    user.id = SnowflakeUtil.generateSnowflakeId();
  });

  // 自定义toJSON方法，避免字段重复
  User.prototype.toJSON = function() {
    const values = Object.assign({}, this.get());

    // 移除重复的下划线字段
    delete values.create_time;
    delete values.update_time;
    delete values.department_id;

    return values;
  };

  // 关联部门
  User.associate = function() {
    app.model.User.belongsTo(app.model.Department, {
      foreignKey: 'department_id',
      as: 'department',
    });

    // 关联角色
    app.model.User.belongsToMany(app.model.Role, {
      through: app.model.UserRole,
      foreignKey: 'user_id',
      otherKey: 'role_code',
      targetKey: 'code', // 指定Role模型的目标键为code
      as: 'roles',
    });
  };

  return User;
};
